package com.hhm.huo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import javax.sql.DataSource;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        UserDetails s;
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username,password,enabled from tb_user where username=?")// 查询用户
                .authoritiesByUsernameQuery("select username,authority from tb_authority where username=?") // 查询权限
                .passwordEncoder(NoOpPasswordEncoder.getInstance());// 密码暗文
     //   super.configure(auth);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //super.configure(http);
        http.authorizeRequests()
                .antMatchers("/login","/user/logoutOk","/user/NoLogin","/mylogin.html","/user/foretPassword").permitAll()  //直接放行
                .antMatchers("/**").authenticated()  // 需要认证的 -- 拦截
                .and()
                    //.formLogin().loginPage("/mylogin.html")// 1.自定义登录页面
                    .formLogin().loginPage("/user/NoLogin")// 1.未登录
                    .loginProcessingUrl("/myprocesslogin") // 2.登录处理的路径
                    .successForwardUrl("/user/loginOk")//3、登陆成功后跳转的地址
                    .failureForwardUrl("/user/loginNo")//4.登录失败跳转地址
                    .and().logout().logoutUrl("/logout")//5、登出，不用自己提供
                    .logoutSuccessUrl("/user/logoutOk")// 6、登出后处理地址
        ;
        http.headers().cacheControl();// 不需要缓存控制
        http.csrf().disable();// 禁用跨域攻击
        http.cors(); //允许跨域访问
    }
}
